package com.joysuch.wwyt.patrol.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityDao;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.mh.entity.MhMonitoringType;
import com.joysuch.wwyt.mh.repository.MhMonitoringTypeDao;
import com.joysuch.wwyt.patrol.entity.PatrolCheckItem;
import com.joysuch.wwyt.patrol.entity.PatrolDataType;
import com.joysuch.wwyt.patrol.entity.PatrolOption;
import com.joysuch.wwyt.patrol.entity.vo.CheckItemDetailVo;
import com.joysuch.wwyt.patrol.entity.vo.CheckItemVo;
import com.joysuch.wwyt.patrol.enums.DataTypeEnum;
import com.joysuch.wwyt.patrol.mapper.PatrolCheckItemMapper;
import com.joysuch.wwyt.patrol.mapper.PatrolDataTypeMapper;
import com.joysuch.wwyt.patrol.service.PatrolCheckItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.patrol.service.PatrolOptionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zr
 * @since 2022-02-28
 */
@Service
public class PatrolCheckItemServiceImpl extends ServiceImpl<PatrolCheckItemMapper, PatrolCheckItem> implements PatrolCheckItemService {

    @Autowired
    private PatrolCheckItemMapper patrolCheckItemMapper;
    @Autowired
    private MhMonitoringTypeDao mhMonitoringTypeDao;
    @Autowired
    private PatrolDataTypeMapper patrolDataTypeMapper;
    @Autowired
    private PatrolOptionService patrolOptionService;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;

    @Override
    public Long findCheckItemNumByPointId(Long checkPointId) {
        return patrolCheckItemMapper.findCheckItemNumByPointId(checkPointId);
    }

    @Override
    public Long findEquipmentNumByPointId(Long checkPointId) {
        return patrolCheckItemMapper.findEquipmentNumByPointId(checkPointId);
    }

    @Override
    public List<CheckItemVo> getCheckItemByPointId(Long pointId) {
        //先查出检查点下的检查设备列表基本数据
        List<CheckItemVo> deviceList =  patrolCheckItemMapper.getdeviceByPointId(pointId);
        Map<Long, Integer> deviceStateMap = new HashMap<>();
        // 获取设备状态
        if (CollectionUtil.isNotEmpty(deviceList)) {
            List<Long> productionFacilityIds = deviceList.stream().map(CheckItemVo::getProductionFacilityId).collect(Collectors.toList());
            List<BpProductionFacility> productionFacilityList = bpProductionFacilityDao.findAllById(productionFacilityIds);
            deviceStateMap = productionFacilityList.stream().collect(Collectors.toMap(BpProductionFacility::getId, BpProductionFacility::getState));

        }
        //根据设备id和检查点id查出每个设备在这个检查点下的检查项目
        for (CheckItemVo checkItemVo : deviceList) {
            Long deviceId = checkItemVo.getDeviceId();
            List<CheckItemDetailVo> itemDetailVoList = patrolCheckItemMapper.getCheckItemByPointIdAndDeviceId(pointId,deviceId);
            //根据检查项目的数据类型去查   state查新表    num查监测点数据类型表
            for (CheckItemDetailVo checkItemDetailVo : itemDetailVoList) {
                String dataType = checkItemDetailVo.getDataType();
                if (StringUtils.isNotBlank(dataType)){
                    DataTypeEnum dataTypeEnum = DataTypeEnum.find(dataType);
                    //数据类型id
                    Long dataTypeId = checkItemDetailVo.getDataTypeId();
                    //正常值id
                    Long normalValueId = checkItemDetailVo.getNormalValueId();
                    switch (dataTypeEnum){
                        case NUM:
                            //从监测点数据类型表中查找
                            Optional<MhMonitoringType> mhTypeName = mhMonitoringTypeDao.findById(dataTypeId);
                            mhTypeName.ifPresent(mhMonitoringType -> {
                                checkItemDetailVo.setDataTypeName(mhMonitoringType.getName());
                                checkItemDetailVo.setUnit(mhMonitoringType.getUnit());
                            });
                            break;

                        case TEXT:
                            //不用查找，没有值
                            break;

                        case SHOCK:
                            PatrolDataType dataTypeByIdShock = patrolDataTypeMapper.findDataTypeByIdShock(dataTypeId);
                            if(null !=dataTypeByIdShock){
                                checkItemDetailVo.setDataTypeId(dataTypeId);
                                checkItemDetailVo.setDataTypeName(dataTypeByIdShock.getDataName());
                            }
                            break;

                        case STATE:
                            //从新的状态表中查找数据类型名称
                            PatrolDataType dataType1 =  patrolDataTypeMapper.findDataTypeById(dataTypeId);
                            if (null != dataType1){
                                checkItemDetailVo.setDataTypeId(dataTypeId);
                                checkItemDetailVo.setDataTypeName(dataType1.getDataName());
                                checkItemDetailVo.setSingletonChoiceFlag(dataType1.getSingletonChoiceFlag());
                            }

                            //查找正常值
                            String normalValueName = patrolDataTypeMapper.findOptionNameById(normalValueId);
                            checkItemDetailVo.setNormalValueId(normalValueId);
                            checkItemDetailVo.setNormalValueName(normalValueName);
                            break;
                    }
                }
            }
            checkItemVo.setCheckItemDetailVoList(itemDetailVoList);
            checkItemVo.setState(deviceStateMap.get(checkItemVo.getProductionFacilityId()));
        }
        return deviceList;
    }

    @Override
    public void delByIds(List<Long> delItemIds) {
        patrolCheckItemMapper.delByIds(delItemIds);
    }

    @Override
    public void delByDeviceIdsAndPointId(List<Long> delDeviceIds, Long pointId) {
        patrolCheckItemMapper.delByDeviceIdsAndPointId(delDeviceIds,pointId);
    }

    @Override
    public String findPointByoptionId(List<Long> optionIds) {
        StringBuilder errMes = new StringBuilder();
        for (Long optionId : optionIds) {
            List<String> pointNameList = patrolCheckItemMapper.getPointByOptionId(optionId);
            if (CollectionUtil.isNotEmpty(pointNameList)){
                PatrolOption option = patrolOptionService.getById(optionId);
                String optionName = null;
                if (null != option){
                    optionName = option.getOptionUnit();
                }
                String pointNames = pointNameList.stream().map(Object::toString).collect(Collectors.joining(Constant.SPLIT_COMMA));
                String result = String.format("选项{%s}已被{%s}检查点绑定,请检查", optionName, pointNames);
                if (StringUtils.isNotBlank(errMes)){
                    errMes.append("\r\n");
                }
                errMes.append(result);
            }
        }
        return errMes.toString();
    }

    @Override
    //查出基本数据
    public List<CheckItemDetailVo> getPointCheckItemData(Long pointId) {
        List<CheckItemDetailVo> result = patrolCheckItemMapper.getByPointId(pointId);
        List<CheckItemDetailVo> defObjs = patrolCheckItemMapper.getDefObjByPointId(pointId);
        result.addAll(defObjs);
        if (CollectionUtil.isNotEmpty(result)){
            //根据数据类型开始赋值
            for (CheckItemDetailVo detailVo : result) {
                DataTypeEnum dataTypeEnum = DataTypeEnum.find(detailVo.getDataType());
                switch (dataTypeEnum){
                    case NUM:
                        //从监测点数据类型表中查找
                        Optional<MhMonitoringType> mhTypeName = mhMonitoringTypeDao.findById(detailVo.getDataTypeId());
                        if (mhTypeName.isPresent()){
                            MhMonitoringType mhMonitoringType = mhTypeName.get();
                            if (StringUtils.isNotBlank(mhMonitoringType.getUnit())){
                                detailVo.setDataTypeName(mhMonitoringType.getName() + "(" + mhMonitoringType.getUnit() + ")");
                            }else {
                                detailVo.setDataTypeName(mhMonitoringType.getName());
                            }
                        }
                        break;

                    case TEXT:
                        //不用查找，没有值
                        break;

                    case STATE:
                        //从新的状态表中查找数据类型名称
                        PatrolDataType dataType =  patrolDataTypeMapper.findDataTypeById(detailVo.getDataTypeId());
                        if (null != dataType){
                            detailVo.setDataTypeName(dataType.getDataName());
                            detailVo.setSingletonChoiceFlag(dataType.getSingletonChoiceFlag());
                        }

                        //查找正常值
                        String normalValueName = patrolDataTypeMapper.findOptionNameById(detailVo.getNormalValueId());
                        detailVo.setNormalValueName(normalValueName);
                        break;
                    case SHOCK:
                        PatrolDataType dataTypeShock =  patrolDataTypeMapper.findDataTypeByIdShock(detailVo.getDataTypeId());
                        if(null !=dataTypeShock){
                            detailVo.setDataTypeName(dataTypeShock.getDataName());
                        }
                        break;
                }
            }


        }
        return result;
    }
}
